﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sausage.Common;
using Sausage.Web.Domain;

namespace Sausage.Web.Code
{
    /// <summary>
    /// 用户认证特性。
    /// </summary>
    /// <remarks></remarks>
    /// <history>
    /// [zanezeng]               2012/03/09 10:56    创建
    /// </history>
    public class RequireAuthorizationAttribute : ActionFilterAttribute
    {
        #region ---Public Method

        /// <summary>
        /// 当Action准备执行时促发。
        /// </summary>
        /// <param name="filterContext">上下文。</param>
        /// <remarks></remarks>
        /// <history>
        /// [zanezeng]               2012/03/09 11:04    创建
        /// </history>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                //获得当前主体
                var principal = Helper.CurrentPrincipal;

                //获得允许的Url列表
                var urlList = principal.MeanList.Select(menu => menu.Menu.SourceUrl).ToList<string>();

                //获得控制器的名称
                string urlController = filterContext.RouteData.Values["controller"] as string;

                //获得行为的名称
                string urlAction = filterContext.RouteData.Values["action"] as string;

                //检查是否授权
                if (!urlList.Contains(string.Format("/{0}/{1}", urlController, urlAction)))
                {
                    //抛出尚未授权异常
                    throw new UnauthorizedException("您尚未授权访问此信息，请联系系统管理员获得此信息访问授权。");
                }
            }
            else
            {
                //抛出尚未认证异常
                throw new UnauthenticatedException("您尚未登录，无法浏览此信息，请登录系统之后再试。");
            }
        } 
        #endregion
    }
}